package com.das.mechanic_base.widget;

import android.content.Context;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.das.mechanic_base.R;
import com.das.mechanic_base.adapter.maintain.X3AloneServiceAdapter;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.base.X3BaseBottomSheetDialog;
import com.das.mechanic_base.base.X3IBaseView;
import com.das.mechanic_base.bean.camera.CameraBean;
import com.das.mechanic_base.bean.greendao.AloneServiceListBean;
import com.das.mechanic_base.bean.greendao.AloneServiceNewBean;
import com.das.mechanic_base.bean.main.HomeMainCarBean;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

public class X3BottomAlreadyAloneServiceDialog extends X3BaseBottomSheetDialog implements X3NewBottomMileOrTimeDialog.IOnAffirmSelect, X3AloneServiceAdapter.IOnClickModify, View.OnClickListener {

    private TextView tv_name;
    private RecyclerView rlv_service;
    private X3AloneServiceAdapter serviceAdapter;
    private long workBaseId;
    private X3NewBottomMileOrTimeDialog mileOrTimeDialog;
    private List<AloneServiceNewBean> mList;
    private boolean needUpdateMile;
    private X3BottomAffirmMileDialog mileDialog;
    private HomeMainCarBean carBean;
    private LinearLayout ll_clear;
    private X3PointDialog pointDialogall;

    public X3BottomAlreadyAloneServiceDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected boolean getDialogCancel() {
        return false;
    }

    @Override
    protected void initView() {
        tv_name = findViewById(R.id.tv_name);
        rlv_service = findViewById(R.id.rlv_service);
        ll_clear = findViewById(R.id.ll_clear);
        ll_clear.setOnClickListener(this);
        rlv_service.setLayoutManager(new LinearLayoutManager(mContext));
        serviceAdapter = new X3AloneServiceAdapter(mContext);
        rlv_service.setAdapter(serviceAdapter);
        serviceAdapter.setiOnClickModify(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.x3_already_alone_add_service;
    }

    /**
     * 开始请求数据
     * 1.先从本地缓存中获取
     * 2.如果本地缓存不存在 那么将从网络上拉取
     * @param workBaseId
     */
    public void getCurrentDetectionList(long workBaseId, boolean needUpdateMile, HomeMainCarBean mainCarBean) {
        this.workBaseId = workBaseId;
        this.needUpdateMile = needUpdateMile;
        this.carBean = mainCarBean;
        NetWorkHttp.getApi().getTouchServiceList(workBaseId)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<List<AloneServiceNewBean>>() {
                    @Override
                    protected void onDone(List<AloneServiceNewBean> mList) {
                        X3BottomAlreadyAloneServiceDialog.this.mList = mList;
                        if (serviceAdapter != null) {
                            serviceAdapter.setData(mList);
                        }
                        ll_clear.setVisibility(X3StringUtils.isListEmpty(mList) ? View.GONE : View.VISIBLE);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });

    }

    @Override
    public void iOnClickModify(AloneServiceNewBean.DetectionTouchServiceEntityListBean bean,long questionBaseId) {
        AloneServiceListBean listBean = new AloneServiceListBean();
        listBean.setCurrentMiles(bean.currentMiles);
        listBean.setPerMiles(bean.perMiles);
        listBean.setId((long) bean.id);
        listBean.setRecommendSafeMiles(bean.recommendSafeMiles);
        listBean.setTouchServiceSn(bean.touchServiceSn);
        listBean.setReductionType(bean.reductionType);
        listBean.setWarningDate(bean.warningDate);
        if (!needUpdateMile) {
            mileOrTimeDialog = new X3NewBottomMileOrTimeDialog(mContext,1);
            mileOrTimeDialog.show();
            mileOrTimeDialog.showCurrentMile(listBean,listBean.getReductionType());
            mileOrTimeDialog.setiOnAffirmSelect(this);
        }else {
            // 否则需要先确认总里程和日均里程
            mileDialog = new X3BottomAffirmMileDialog(mContext);
            mileDialog.show();
            mileDialog.setWorkBaseId(workBaseId,carBean);
            mileDialog.setiOnClickAffirmMiles((currentMiles1, perMiles1) -> {
                // 确认完总里程和日均里程了
                needUpdateMile = false;
                EventBus.getDefault().post(new CameraBean(X3Constent.CODE_ALONE_CHANGE_NEED_UPDATE,""));

                double newPerMiles = Double.parseDouble(X3StringUtils.formatDouble(perMiles1));
                double newCurrentMile = Double.parseDouble(X3StringUtils.formatDouble(currentMiles1));

                getCurrentDetectionList(workBaseId,needUpdateMile,carBean);

                listBean.setCurrentMiles(newCurrentMile);
                listBean.setPerMiles(newPerMiles);

                mileOrTimeDialog = new X3NewBottomMileOrTimeDialog(mContext,1);
                mileOrTimeDialog.show();
                mileOrTimeDialog.showCurrentMile(listBean,listBean.getReductionType());
                mileOrTimeDialog.setiOnAffirmSelect(this);
            });
        }
    }

    @Override
    public void iOnAffirmMiles(AloneServiceListBean listBean) {
        saveDetectionService(listBean);
    }

    private void saveDetectionService(AloneServiceListBean bean) {
        NetWorkHttp.getApi().updateDeService(bean)
                .compose(((X3IBaseView)mContext).bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<Object>() {
                    @Override
                    protected void onDone(Object o) {
                        aloneRefresh();
                        getCurrentDetectionList(workBaseId,needUpdateMile,carBean);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @Override
    public void iOnPickerDismiss() {

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.ll_clear) {
            showClearDialog();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        MobclickAgent.onPageStart("推荐项目清单弹窗");
    }

    @Override
    protected void onStop() {
        super.onStop();
        MobclickAgent.onPageEnd("推荐项目清单弹窗");
    }

    @Override
    public void iOnClickModifyDel(AloneServiceNewBean.DetectionTouchServiceEntityListBean delBean, long questionBaseId,int position,int positionSec) {//删除
        if(delBean.systemTouched){
            X3ToastUtils.showMessage(mContext.getString(R.string.no_can_delete_item));
            return;
        }
        showDelDialog(delBean,questionBaseId,position,positionSec);

    }

    /**
     * 清空购物车
     * @param workBaseId
     */
    private void delAllTouchService(long workBaseId) {
        NetWorkHttp.getApi().delAllTouchService(workBaseId)
                .compose(((X3IBaseView)mContext).bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<Object>() {
                    @Override
                    protected void onDone(Object o) {
                        aloneRefresh();
                        getCurrentDetectionList(workBaseId,needUpdateMile,carBean);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    private void showDelDialog(AloneServiceNewBean.DetectionTouchServiceEntityListBean delBean, long questionBaseId,int position,int positionSec) {
        X3PointDialog pointDialog = new X3PointDialog(mContext,"",mContext.getString(R.string.confirm_del_the_recommend),
                mContext.getString(R.string.x3_cancel_info),mContext.getString(R.string.x3_affirm_string));
        pointDialog.show();
        pointDialog.setiBtnClick(new X3PointDialog.IBtnClick() {
            @Override
            public void iBtnAffirmClick() {

                if (pointDialog != null) {
                    pointDialog.dismiss();
                }
                delDetectionService(delBean.id,questionBaseId,delBean.workBaseId,position,positionSec);

            }

            @Override
            public void iBtnCancelClick() {
                if (pointDialog != null) {
                    pointDialog.dismiss();
                }
            }
        });
    }

    private void showClearDialog() {


        int system =0;
        int notsystem = 0;
        if(serviceAdapter == null) {
            return;
        }
            List<AloneServiceNewBean> list = serviceAdapter.getmList();
            if(X3StringUtils.isListEmpty(list)){
                return;
            }
            for (int i = 0; i < list.size();i++){
                List<AloneServiceNewBean.DetectionTouchServiceEntityListBean> mlist = list.get(i).detectionTouchServiceEntityList;
                for (int j = 0;j < mlist.size();j++){
                    if(mlist.get(j).systemTouched){//系统推荐的
                        system++;

                    }else{
                        notsystem++;
                    }
                }
            }
        if((system == 0 && notsystem == 0) || (system == 1 && notsystem == 1)){
            pointDialogall = new X3PointDialog(mContext,"",mContext.getString(R.string.del_manual_recommend),
                    mContext.getString(R.string.x3_cancel_info),mContext.getString(R.string.x3_affirm_string));
        }else if(system >= 2 &&  notsystem >= 2){
            pointDialogall = new X3PointDialog(mContext,"",mContext.getString(R.string.del_manual_recommend_one),
                    mContext.getString(R.string.x3_cancel_info),mContext.getString(R.string.x3_affirm_string));
        }else if(system >= 2 &&  notsystem == 0){
            X3ToastUtils.showMessage(mContext.getString(R.string.no_can_delete_items));
            return;
//            pointDialogall = new PointDialog(mContext,"",mContext.getString(R.string.del_manual_recommend_two),
//                    mContext.getString(R.string.cancel_info),mContext.getString(R.string.affirm_string));
        }else {
            pointDialogall = new X3PointDialog(mContext,"",mContext.getString(R.string.del_manual_recommend_three),
                    mContext.getString(R.string.x3_cancel_info),mContext.getString(R.string.x3_affirm_string));
        }


        pointDialogall.show();
        pointDialogall.setiBtnClick(new X3PointDialog.IBtnClick() {
            @Override
            public void iBtnAffirmClick() {

                if (pointDialogall != null) {
                    pointDialogall.dismiss();
                }
                delAllTouchService(workBaseId);
            }

            @Override
            public void iBtnCancelClick() {
                if (pointDialogall != null) {
                    pointDialogall.dismiss();
                }
            }
        });
    }

    /**
     * 删除
     * @param detectionTouchServiceId
     * @param questionBaseId
     * @param workBaseId
     * @param position
     * @param positionSec
     */
    private void delDetectionService(long detectionTouchServiceId,long questionBaseId,long workBaseId,int position,int positionSec) {
        NetWorkHttp.getApi().delDetectionService(detectionTouchServiceId,questionBaseId,workBaseId)
                .compose(((X3IBaseView)mContext).bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<Object>() {
                    @Override
                    protected void onDone(Object o) {
                        if(serviceAdapter != null){
                            serviceAdapter.delItem(position,positionSec);
                            List<AloneServiceNewBean> aloneServiceNewBeans = serviceAdapter.getmList();
                            if(X3StringUtils.isListEmpty(aloneServiceNewBeans)){
                                ll_clear.setVisibility(View.GONE);
                            }else {
                                ll_clear.setVisibility(View.VISIBLE);
                            }
                            aloneRefresh();
                        }

                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    public void aloneRefresh(){
        EventBus.getDefault().post(new CameraBean(X3Constent.CODE_ALONE_ADD_SERVICE_REQUEST, ""));

        CameraBean cameraBean = new CameraBean(X3Constent.CODE_ALONE_ADD_SERVICE_REFRESH,1);
        EventBus.getDefault().post(cameraBean);
    }
}
